package com.zlm.custom.proxy;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author zlm
 * @date 2025/4/22
 */
public class Compiler {

    public static void compile(File javaFile){
        System.out.println("编译java文件");
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        //获取文件管理器
        try(StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)){
            List<File> list = new ArrayList<>();
            list.add(javaFile);
            //获取文件要编译的对象
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(list);
            //设置编译选项
            List<String> optionList = Arrays.asList("-d","./target/classes");

            //创建编译任务
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, optionList, null, compilationUnits);

            //执行编译任务
            Boolean call = task.call();
            if (call){
                System.out.println("编译成功");
            }else {
                System.out.println("编译失败");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
